/**
 * 自定义看板娘脚本
 * 基于live2d-widget项目进行修改和适配
 */

// 全局配置
window.live2d_settings = {
  // 基本设置
  modelAPI: 'https://api.fghrsh.net/live2d/',
  tipsMessage: '欢迎来到二次元世界~',
  hitokotoAPI: 'https://v1.hitokoto.cn',

  // 设置御姐风格的模型 (6号模型，2号材质)
  modelId: 6,
  modelTexturesId: 2,

  // 允许拖动
  waifuDraggable: 'unlimited',
  waifuDraggableRevert: false,

  // 工具栏设置
  showToolMenu: true,
  canCloseLive2d: true,
  canSwitchModel: true,
  canSwitchTextures: true,
  canSwitchHitokoto: true,
  canTakeScreenshot: true,

  // 提示消息设置
  showHitokoto: true,
  showF12Status: true,
  showCopyMessage: true,

  // 样式设置
  waifuSize: '180x180',
  waifuTipsSize: '200x70',
  waifuFontSize: '12px',
  waifuToolFont: '14px',
  waifuToolLine: '20px',
  waifuToolTop: '0px',
  waifuMinWidth: '768px',

  // 自定义提示语
  waifu: {
    console_open_msg: ['哎呀，你打开了控制台，是想要看到我的小秘密吗？'],
    copy_message: ['你都复制了些什么呀，转载要记得加上出处哦'],
    screenshot_message: ['照好了吗，是不是很可爱呢？'],
    hidden_message: ['我还在这里，等你回来...'],
    load_failed_message: ['模型加载失败，请刷新页面'],
    welcome_message: ['欢迎来到星穹铁道的世界~'],
  },
}

/**
 * 初始化看板娘
 */
export function initLive2D() {
  console.log('初始化看板娘 - 御姐风格')

  // 检查是否显示看板娘
  const showLive2D = localStorage.getItem('showLive2D')
  if (showLive2D === 'false') {
    console.log('看板娘已设置为隐藏状态')
    return
  }

  // 直接使用CDN加载看板娘
  loadLive2DCDN()
}

/**
 * 从CDN加载看板娘
 */
function loadLive2DCDN() {
  // 创建script标签
  const scriptElement = document.createElement('script')
  scriptElement.src =
    'https://cdn.jsdelivr.net/gh/stevenjoezhang/live2d-widget@latest/autoload.js'
  scriptElement.id = 'live2d-direct-script'

  // 错误处理
  scriptElement.onerror = () => {
    console.error('看板娘脚本加载失败，尝试使用备用方法')
    setupManualLive2D()
  }

  // 添加到body
  document.body.appendChild(scriptElement)

  // 设置轮询检查确保显示
  const monitorInterval = setInterval(() => {
    const waifuElement = document.querySelector('.waifu')
    if (waifuElement) {
      // 调整样式以确保显示
      waifuElement.style.zIndex = '10000'
      waifuElement.style.display = 'block'
      waifuElement.style.visibility = 'visible'
      waifuElement.style.opacity = '1'
      waifuElement.style.width = '180px'
      waifuElement.style.height = '180px'
      waifuElement.style.cursor = 'move'

      // 检查canvas元素
      const canvasElement = document.getElementById('live2d')
      if (canvasElement) {
        canvasElement.style.display = 'block'
        canvasElement.style.visibility = 'visible'
        canvasElement.style.opacity = '1'
        canvasElement.style.width = '180px'
        canvasElement.style.height = '180px'
      }
    } else {
      // 如果看板娘元素不存在，重新尝试加载
      if (!document.getElementById('live2d-direct-script')) {
        document.body.appendChild(scriptElement.cloneNode(true))
      }
    }
  }, 3000)

  // 返回清理函数
  return () => {
    clearInterval(monitorInterval)
  }
}

/**
 * 手动设置看板娘
 */
function setupManualLive2D() {
  // 手动创建DOM结构
  createDOM()

  // 加载CSS
  loadCSS()

  // 加载必要脚本
  loadScript(
    'https://cdn.jsdelivr.net/gh/stevenjoezhang/live2d-widget@latest/waifu-tips.js',
    () => {
      loadScript(
        'https://cdn.jsdelivr.net/gh/stevenjoezhang/live2d-widget@latest/live2d.min.js',
        () => {
          // 确保live2d加载完成后再加载模型
          if (window.loadlive2d) {
            const modelUrl = `https://api.fghrsh.net/live2d/get/?id=6-2`
            window.loadlive2d('live2d', modelUrl)
            console.log('看板娘模型加载完成')
          }
        },
      )
    },
  )

  // 启用拖动
  setupDraggable()

  // 定期检查看板娘是否被隐藏，如果被隐藏则重新显示
  const checkVisibility = setInterval(() => {
    const widget = document.getElementById('live2d-widget')
    const canvas = document.getElementById('live2d')

    // 检查是否显示看板娘
    const showLive2D = localStorage.getItem('showLive2D')
    if (showLive2D === 'false') {
      // 如果设置为不显示，则隐藏看板娘
      if (widget) widget.style.display = 'none'
      return
    }

    if (widget) {
      if (
        widget.style.display === 'none' ||
        widget.style.visibility === 'hidden' ||
        widget.style.opacity === '0'
      ) {
        console.log('看板娘被隐藏，重新显示')
        widget.style.display = 'block'
        widget.style.visibility = 'visible'
        widget.style.opacity = '1'
        widget.style.width = '180px'
        widget.style.height = '180px'
      }
    }

    if (canvas) {
      if (
        canvas.style.display === 'none' ||
        canvas.style.visibility === 'hidden' ||
        canvas.style.opacity === '0'
      ) {
        console.log('看板娘画布被隐藏，重新显示')
        canvas.style.display = 'block'
        canvas.style.visibility = 'visible'
        canvas.style.opacity = '1'
        canvas.style.width = '180px'
        canvas.style.height = '180px'
      }
    }
  }, 2000)

  // 返回清理函数
  return () => {
    clearInterval(checkVisibility)
  }
}

/**
 * 创建DOM结构
 */
function createDOM() {
  // 检查是否已经存在
  if (document.getElementById('live2d-widget')) {
    console.log('看板娘容器已存在，跳过创建')
    return
  }

  const container = document.createElement('div')
  container.id = 'live2d-widget'
  container.className = 'live2d-widget-container'
  container.style.position = 'fixed'
  container.style.right = '20px'
  container.style.bottom = '0'
  container.style.width = '180px'
  container.style.height = '180px'
  container.style.zIndex = '10000'
  container.style.pointerEvents = 'auto'
  container.style.display = 'block'
  container.style.opacity = '1'
  container.style.visibility = 'visible'
  container.style.cursor = 'move'

  document.body.appendChild(container)

  // 添加内部结构
  container.innerHTML = `
    <div class="waifu">
      <div class="waifu-tips" style="opacity:1;"></div>
      <canvas id="live2d" width="180" height="180" style="position:relative;opacity:1;display:block;"></canvas>
      <div class="waifu-tool">
        <span class="fa fa-commenting"></span>
        <span class="fa fa-user-circle"></span>
        <span class="fa fa-street-view"></span>
        <span class="fa fa-camera"></span>
        <span class="fa fa-info-circle"></span>
      </div>
    </div>
  `
}

/**
 * 添加拖动功能
 */
function setupDraggable() {
  setTimeout(() => {
    const widget = document.getElementById('live2d-widget')
    if (widget) {
      widget.style.pointerEvents = 'auto'
      widget.style.cursor = 'move'

      let isDragging = false
      let offsetX = 0
      let offsetY = 0

      widget.addEventListener('mousedown', (e) => {
        isDragging = true
        offsetX = e.clientX - widget.getBoundingClientRect().left
        offsetY = e.clientY - widget.getBoundingClientRect().top
        widget.style.transition = 'none'
      })

      document.addEventListener('mousemove', (e) => {
        if (isDragging) {
          widget.style.left = e.clientX - offsetX + 'px'
          widget.style.right = 'auto'
          widget.style.top = e.clientY - offsetY + 'px'
          widget.style.bottom = 'auto'
        }
      })

      document.addEventListener('mouseup', () => {
        isDragging = false
        widget.style.transition = 'all 0.3s ease'
      })
    }
  }, 2000)
}

/**
 * 加载CSS
 */
function loadCSS() {
  if (document.querySelector('link[href*="live2d-widget"]')) {
    return
  }

  const link = document.createElement('link')
  link.rel = 'stylesheet'
  link.type = 'text/css'
  link.href =
    'https://cdn.jsdelivr.net/gh/stevenjoezhang/live2d-widget@latest/waifu.css'
  document.head.appendChild(link)
}

/**
 * 加载脚本
 */
function loadScript(url, callback) {
  const script = document.createElement('script')
  script.src = url
  script.onload = callback
  document.body.appendChild(script)
}
